package lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 混合锁:  自旋锁+互斥锁
 *
 *
 * @author 1
 * @version 1.0
 * @description: TODO
 * @date 2024-11-28 11:42
 */

public class HybridLock {
    private final Lock lock = new ReentrantLock();
    private volatile boolean locked = false;

    public void lock() {
        long start = System.nanoTime();
        long spinTimeNanos = 10_000_000; // 自旋时间，单位为纳秒（10毫秒）

        // 尝试自旋锁
        while (locked) {
            if (System.nanoTime() - start > spinTimeNanos) {
                break; // 超过自旋时间，转为互斥锁
            }
            // 提示JVM当前线程正在自旋,让JVM采取优化措施
            Thread.onSpinWait();
        }

        // 如果自旋锁未成功，使用互斥锁
        if (locked) {
            lock.lock();
            try {
                // 确保互斥锁获取成功后，设置locked为true
                locked = true;
            } finally {
                lock.unlock();
            }
        } else {
            locked = true;
        }
    }

    public void unlock() {
        lock.lock();
        try {
            locked = false;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        HybridLock hybridLock = new HybridLock();

        //多线程
        Runnable task = () -> {
            hybridLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " acquired the lock");
                Thread.sleep(2000); // 模拟长时间持有锁
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                hybridLock.unlock();
                System.out.println(Thread.currentThread().getName() + " released the lock");
            }
        };

        Thread t1 = new Thread(task, "Thread-1");
        Thread t2 = new Thread(task, "Thread-2");

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

